package cn.magicman.demo;

import java.util.Queue;
import java.util.LinkedList;

class MessageQueue {
    private Queue<String> queue = new LinkedList<>();
    private int maxSize = 5;

    public synchronized void produce(String message) throws InterruptedException {
        while (queue.size() == maxSize) {
            System.out.println("队列已满，生产者等待...");
            wait(); // 队列满，等待
        }
        queue.add(message);
        System.out.println("生产消息: " + message + " (队列大小: " + queue.size() + ")");
        notifyAll(); // 通知消费者
    }

    public synchronized String consume() throws InterruptedException {
        while (queue.isEmpty()) {
            System.out.println("队列为空，消费者等待...");
            wait(); // 队列空，等待
        }
        String message = queue.poll();
        System.out.println("消费消息: " + message + " (队列大小: " + queue.size() + ")");
        notifyAll(); // 通知生产者
        return message;
    }
}

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        MessageQueue messageQueue = new MessageQueue();
        
        // 创建生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    messageQueue.produce("消息-" + i);
                    Thread.sleep((long)(Math.random() * 1000)); // 模拟生产时间
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        // 创建消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    messageQueue.consume();
                    Thread.sleep((long)(Math.random() * 1500)); // 模拟消费时间
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        // 启动线程
        producer.start();
        consumer.start();
        
        // 等待线程结束
        try {
            producer.join();
            consumer.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        System.out.println("程序运行结束");
    }
}